//导入数据库连接模块
const db = require('../db/index');

const answerModel = db.model('answer', {
  __v: { type: Number, select: false },
  paperid: { type: String, require: true },
  answerInfo: { type: Object },
  ctime: { type: Date, default: Date.now },
  utime: { type: Date },
});

module.exports = {
  // 添加答卷
  addAnswer(info) {
    // console.log(info);
    const answer = new answerModel(info);
    return answer
      .save()
      .then(res => res)
      .catch(err => {
        console.log('添加失败' + err);
        return false;
      });
  },
  getPaperAnswersCount(ids) {
    return answerModel
      .find({ _id: ids })
      .then(res => {
        return res.length;
      })
      .catch(err => {
        console.log('查询失败' + err);
        return false;
      });
  },
  // 获取答卷
  getAnswers(ids) {
    return answerModel
      .find({ _id: ids }, { answerInfo: 1, ctime: 1 })
      .sort({ ctime: -1 })
      .then(res => {
        return res;
      })
      .catch(err => {
        console.log('查询失败' + err);
        return false;
      });
  },
  // 根据id获取单个答卷
  getAnswerById(_id) {
    // console.log(_id);
    return answerModel
      .findById(_id)
      .then(res => res)
      .catch(err => {
        console.log('查询失败' + err);
        return false;
      });
  },
  // 根据id删除单个答卷
  deleteAnswerById(_id) {
    return answerModel
      .deleteOne({ _id })
      .then(res => {
        return res;
      })
      .catch(err => {
        console.log('删除失败' + err);
        return false;
      });
  },
  // 根据多个ID批量删除答卷
  deleteAnswersByIds(ids) {
    return answerModel
      .deleteMany({ _id: { $in: ids } })
      .then(res => res)
      .catch(err => {
        console.log('删除失败' + err);
        return false;
      });
  },
  // 根据问卷ID删除答卷
  deleteAnswersByPaperid(paperid) {
    return answerModel
      .deleteMany({ paperid })
      .then(res => {
        return res;
      })
      .catch(err => {
        console.log('删除失败' + err);
        return false;
      });
  },
  // 根据ID编辑答卷信息
  updateAnswerById(_id, data) {
    // console.log(data);
    return answerModel
      .updateOne({ _id }, { $set: data, utime: Date.now() })
      .then(res => res)
      .catch(err => {
        console.log('修改失败' + err);
        return false;
      });
  },
  // 判断字段值是否存在
  isExist(field, value) {
    return answerModel
      .findOne({ [field]: value })
      .then(res => res)
      .catch(err => {
        console.log('查询失败' + err);
        return false;
      });
  },
};
